package com.example.demo.controller;

import com.example.demo.controller.requests.ModifyDrinkRequest;
import com.example.demo.model.Drink;
import com.example.demo.service.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static sun.rmi.registry.RegistryImpl.getID;

@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    private IDrinkService drinkService;
    // get /drink/
    // 查询所有
        @GetMapping("/")//@RequestMapping(value = "/",method = RequestMethod.GET)
        public List<Drink> getAll(){
            // 假,mock数据 - 后期从数据库查询
            List<Drink> results=drinkService.getAllDrinks();
            return results;
        }

    // get /drink/1
    // path路径表示法 id=1
    // id查询某一个
        @GetMapping("/{id}")
        public Drink getDrink (@PathVariable Integer id) {
            // 后期从数据库查询   select  ……  where …… id=↑id
            log.info("查询饮品的id:{}", id);// 日志
            Drink drink = Drink.builder().id(1)
                    .name("茉莉花茶")
                    .price(Money.parse("USD 8.00"))
                    .build();
            return drink;
        }
    // 新增
    // post /drink,{"name":"奶茶","price",8.00}
    // 1直接使用model类接受用户参数
        @PostMapping("/")
        public Drink addNewDrink(@RequestBody @Valid Drink drink, BindingResult bindingResult){
            if (bindingResult.hasErrors()) {
                for (ObjectError allError : bindingResult.getAllErrors()) {
                    log.error(allError.toString());
                }
                return null;
            }else {
                log.info("创建新饮品:{}",drink);
                drinkService.addNewDrink(drink);
                return drink;
            }

        }

    // 修改
    // 2编写一个TO类专门负责传值
    // put /drink/{"id":1,"name":"新奶茶","price",10.00}
        @PutMapping("/")
        public Drink modifyDrink(@RequestBody ModifyDrinkRequest request){
            log.info("要修改的饮品:{}",request);
            //通过ID查询出饮品
            Drink drink=drinkService.getDrinkByID(request.getId());
            //复制前端需要修改的属性
            BeanUtils.copyProperties(request,drink);
            //更新数据库
            drinkService.updataDrink(drink);
            return drink;
        }
    // 删除
    // delect /drink/1
    @DeleteMapping("/{id}")
    public String delectDrink(@PathVariable Integer id){
        log.info("要删除的饮品:{}",id);
        drinkService.deleteDrinkById(id);
        return "删除成功";
    }

//    文件上传
//    前端必须使用html from
//    前端类型必须为multipart.from-date
    @PostMapping(value = "/upload",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String uploadFile(MultipartFile file){
        String dest="E:/Desktop/";
        String destfileName=dest+file.getOriginalFilename();
        File destfile=new File(destfileName);
        try {
            file.transferTo(destfile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }
    @PostMapping(value = "/adds",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public List<Drink> batchNewDrink(MultipartFile file) {
            List<Drink> results=new ArrayList<>();
        try {
            BufferedReader reader=new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line="";
            while ((line=reader.readLine())!=null){
                // 解析一行
                String[] args=line.split(",");
                Drink drink =Drink.builder()
                        .id(Integer.parseInt(args[0]))
                        .name(args[1])
                        .price(Money.of(CurrencyUnit.of("CNY"),Double.parseDouble(args[2])))
                        .build();
                results.add(drink);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return results;
    }
}
